package com.ghs.securityprojectboot.controller;

import com.ghs.securityprojectboot.entity.vo.RestBean;
import com.ghs.securityprojectboot.entity.vo.request.ConfirmResetVO;
import com.ghs.securityprojectboot.entity.vo.request.EmailRegisterVO;
import com.ghs.securityprojectboot.entity.vo.request.ResetPasswordVO;
import com.ghs.securityprojectboot.service.IDbAccountService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shenguohui
 * @since 2024-08-31
 */

@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthoritiesController {

    private final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$";

    @Resource
    IDbAccountService dbAccountService;

    @GetMapping("/valid-register-email")
    @Operation(summary = "请求邮件验证码")
    public RestBean<String> askVerifyCode(@RequestParam @Email String email,
                                        @RequestParam @Pattern(regexp = "(register|reset)")  String type,
                                        HttpServletRequest request){
        String s = dbAccountService.sendValidateEmail(email, "reset".equals(type));
        if (s == null)
            return RestBean.success("邮件已发送，请注意查收");
        else
            return RestBean.failure(400, s);
    }
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public RestBean<String> registerUser(@RequestBody @Valid EmailRegisterVO emailRegisterVO) {
        String s = dbAccountService.validateAndRegister(emailRegisterVO);
        if(s == null)
            return RestBean.success("注册成功");
        else
            return RestBean.failure(400, s);
    }
    @PostMapping("/reset-confirm")
    @Operation(summary = "密码重置确认")
    public RestBean<Void> resetConfirm(@RequestBody @Valid ConfirmResetVO vo){
        String reset = dbAccountService.resetConfirm(vo);
        if( reset == null)
            return RestBean.success();
        else
            return RestBean.failure(400, reset);
    }
    /**
     * 执行密码重置操作
     * @param vo 密码重置信息
     * @return 是否操作成功
     */
    @PostMapping("/reset-password")
    @Operation(summary = "密码重置操作")
    public RestBean<Void> resetPassword(@RequestBody @Valid ResetPasswordVO vo){
        String reset = dbAccountService.resetPassWord(vo);
        if( reset == null)
            return RestBean.success();
        else
            return RestBean.failure(400, reset);
    }
}

